package com.ruoyi.system.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.dto.MyOrdersDTO;
import com.ruoyi.system.domain.MealOrder;
import com.ruoyi.system.domain.dto.UnfilledMealOrderDTO;
import com.ruoyi.system.service.IMealOrderService;
import com.ruoyi.system.domain.UserQrcode;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.IUserQrcodeService;
import com.ruoyi.system.utils.QRCodeGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import java.util.List;

@RestController
@RequestMapping("/h5")
public class H5Controller extends BaseController {
    @Autowired
    ISysUserService sysUserService;
    @Autowired
    IMealOrderService mealOrderService;

    @Autowired
    IUserQrcodeService userQrcodeService;

    @Value("${ruoyi.profile}")
    private String uploadPath;

    /**
     * 创建包含用户信息的二维码
     */
    @RequestMapping("/createQRCode")
    public AjaxResult createQRCode() throws Exception {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserId();
        // 查询用户二维码信息
        UserQrcode userQrcode = userQrcodeService.selectUserQrcodeByUserId(userId);
        //生成二维码路径
        String qrCodePath = uploadPath.endsWith("/") || uploadPath.endsWith("\\") ?
                uploadPath + "qrcode/" : uploadPath + "/qrcode/";
        // 生成二维码文件
        String fileName = userId + ".png";
        QRCodeGenerator.generateLargeQRCodeWithoutMargin(userId.toString(), qrCodePath, 400);
        String dbPath = "/profile/qrcode/" + fileName;

        //如果用户记录不存在，则创建新记录；如果存在则更新二维码路径
        if (userQrcode == null) {
            userQrcode = new UserQrcode();
            userQrcode.setUserId(userId);
            userQrcode.setUrl(dbPath);
            userQrcodeService.insertUserQrcode(userQrcode);
        } else {
            userQrcode.setUrl(dbPath);
            userQrcodeService.updateUserQrcode(userQrcode);
        }
        return AjaxResult.success(dbPath);
    }

    /**
     * 获取用户未填写的订单列表
     */
    @RequestMapping("/getUnOrderList")
    public AjaxResult getUnOrderList() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserId();
        List<UnfilledMealOrderDTO> unfilledMealOrders = mealOrderService.getUnfilledMealOrders(userId);
        return AjaxResult.success(unfilledMealOrders);

    }

    /**
     * 核销订餐
     */
    @RequestMapping("/verify")
    public AjaxResult verify(Long userID) {
        try {
            MealOrder mealOrder = new MealOrder();
            mealOrder.setEmpId(userID);
            List<MealOrder> list = mealOrderService.selectMealOrderList(mealOrder);
            // 获取当前时间
            Date now = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String currentDate = sdf.format(now);
            // 判断当前是午餐时间还是晚餐时间
            String currentMealType = mealOrderService.getCurrentMealType(now);
            if (currentMealType == null) {
                return AjaxResult.success("非用餐核销时间");
            }
            // 查找当天对应餐别的订单
            MealOrder targetOrder = mealOrderService.findTargetOrder(list, currentDate, currentMealType, sdf);
            if (targetOrder == null) {
                return AjaxResult.success("未找到符合条件的订餐记录");
            }
            // 检查订单状态
            if (targetOrder.getIsOrdered() == null || targetOrder.getIsOrdered() != 1) {
                return AjaxResult.success("该用户未订餐，无法核销");
            }
            // 执行核销操作
            targetOrder.setIsOrdered(2); // 2表示已核销
            targetOrder.setVerifyTime(now);
            mealOrderService.updateOrder(targetOrder);
            return AjaxResult.success("核销成功");
        } catch (Exception e) {
            logger.error("核销订餐失败", e);
            return AjaxResult.success("核销失败: " + e.getMessage());
        }

    }

    /**
     * 获取我的订单列表
     */
    @RequestMapping("/getMyOrderList")
    public AjaxResult getMyOrderList() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserId();
        MyOrdersDTO myOrders = mealOrderService.getMyOrders(userId);
        return AjaxResult.success(myOrders);
    }

    /**
     * 修改员工订餐状态
     *
     * @param id 订单id
     * @param status 状态值
     */
    @RequestMapping("/alterStatus")
    public AjaxResult alterStatus(Long id, Integer status){
        return success( mealOrderService.alterMealOrderStatus(id,status));
    }
}
